package net.whzjkj.gateway.core.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import net.whzjkj.gateway.core.config.NettyConfig;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;

/**
 * @description:
 * @author: Mr.Hu
 * @create: 2018-11-05 16:58
 **/
@Slf4j
public abstract class AbstractNettyServer implements NettyServer{

    /**
     * 用于管理所有的channel
     */
    public static final ChannelGroup ALL_CHANNELS = new DefaultChannelGroup("TERMINAL-CHANNELS", GlobalEventExecutor.INSTANCE);

    @Autowired
    protected NettyConfig nettyConfig;
    //@Autowired
    protected ChannelInitializer<? extends Channel> channelInitializer;


    @Override
    public void startServer(int port) throws Exception {
        nettyConfig.setPort(port);
        nettyConfig.setSocketAddress(nettyConfig.getSocketAddress());
        startServer();
    }

    @Override
    public void startServer(InetSocketAddress socketAddress) throws Exception {
        nettyConfig.setSocketAddress(socketAddress);
        startServer();
    }

    @Override
    public void stopServer() throws Exception {
        log.debug("In stopServer method of class: {}", this.getClass().getName());
        ChannelGroupFuture future = ALL_CHANNELS.close();
        try {
            future.await();
        } catch (InterruptedException e) {
            log.error("Execption occurred while waiting for channels to close: {}",e);
        } finally {
            if (null != nettyConfig.getBossGroup()) {
                nettyConfig.getBossGroup().shutdownGracefully();
            }
            if (null != nettyConfig.getWorkerGroup()) {
                nettyConfig.getWorkerGroup().shutdownGracefully();
            }
        }
    }

    @Override
    public InetSocketAddress getSocketAddress() {
        return nettyConfig.getSocketAddress();
    }

    @Override
    public ChannelInitializer<? extends Channel> getChannelInitializer() {
        return channelInitializer;
    }

    /**
     * 获取bossGroup，在spring中配置
     * @return
     */
    protected EventLoopGroup getBossGroup(){
        return nettyConfig.getBossGroup();
    }

    /**
     * 获取workerGroup， 在spring中配置
     * @return
     */
    protected EventLoopGroup getWorkerGroup(){
        return nettyConfig.getWorkerGroup();
    }

}
